package com.doodle.common.utils;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

public abstract class BaseListAdapter<T> extends BaseAdapter {

	protected List<T> mDataList;
	protected Context mContext;
	
	public void swapData(List<T> dataList) {
		if (mDataList != dataList) {
			onDataChanged(dataList);
			mDataList = dataList;
		}
		notifyDataSetChanged();
	}
	
	@Override
	public int getCount() {
		return mDataList == null ? 0 : mDataList.size();
	}

	@Override
	public Object getItem(int position) {
		if (mDataList == null || position < 0 || position >= getCount()) {
			return null;
		} else {
			return mDataList.get(position);
		}
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressWarnings("unchecked")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		T data = (T)getItem(position);
		if (data == null) {
			throw new IllegalStateException("couldn't move datalist to position " + position);
		}

		View v = convertView;
		if (v == null) {
			v = newView(mContext, position, mDataList);
		}
		bindView(v, mContext, position, data);
		return v;
	}
	
	protected void onDataChanged(List<T> dataList) {
	}
	
	public List<T> getData() {
		return mDataList;
	}
	
	public Context getContext() {
		return mContext;
	}

	protected abstract void bindView(View view, Context context, int position, T data);
	protected abstract View newView(Context context, int postion, List<T> dataList);
}
